//
//  ScreentoneViewController.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/10/10.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "ScreentoneViewController.h"
#import "CBaseTable.h"
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "ScreentoneView.h"
#import "ScreentoneModel.h"
@interface ScreentoneViewController ()<UISearchBarDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,UITextFieldDelegate>
{
    
    NSMutableArray *_dataArray;
    NSString *_searchText;
    double _longitude;
    double _latitude;
    BMKLocationService* _locService;
    BMKGeoCodeSearch *_geocodesearch;
    BOOL isGeoSearch;
}
@property (nonatomic, strong)ScreentoneView  *table;
@property (nonatomic, strong) UITextField *searchField;

@end

@implementation ScreentoneViewController

- (void)initView {
    [super initView];
    self.navBar.hidden=NO;
    [self setTitle:@"选择机构"];
   
    _dataArray=[[NSMutableArray alloc]init];
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    //编码服务的初始化(就是获取经纬度,或者获取地理位置服务)
    _geocodesearch.delegate = self;//设置代理为self
    UIView *searchView=[[UIView alloc]initWithFrame:CGRectMake(0, 64, WindowWidth, 40)];
    searchView.backgroundColor=BackColor;
    [self.view addSubview:searchView];
    _searchField = [[UITextField alloc]initWithFrame:CGRectMake(10, 5, WindowWidth-60, 30)];
    _searchField.delegate = self;
    _searchField.backgroundColor=[UIColor whiteColor];
    _searchField.layer.masksToBounds=YES;
    _searchField.layer.cornerRadius=2;
    _searchField.placeholder = @"搜索";
    _searchField.font=FF(15);
    _searchField.returnKeyType=UIReturnKeyDone;
    _searchField.clearButtonMode=UITextFieldViewModeAlways;
    [searchView addSubview:_searchField];
    UIButton *backBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame=CGRectMake(CGRectGetMaxX(_searchField.frame)+10, 0, 40, 40);
    [backBtn setTitle:@"取消" forState:UIControlStateNormal];
    [backBtn setTitleColor:MainColor forState:UIControlStateNormal];
    backBtn.titleLabel.font=FF(16);
    [searchView addSubview:backBtn];
    [backBtn bk_addEventHandler:^(id sender) {
        
        _searchField.text = nil;
        [_table setDicParam:nil];
        [_searchField resignFirstResponder];
    } forControlEvents:UIControlEventTouchUpInside];


  _table =[[ScreentoneView alloc]initWithFrame:CGRectMake(0, 104, WindowWidth, WindowHeight-CGRectGetMaxY(searchView.frame))];
  _table.separatorStyle =UITableViewCellSelectionStyleNone;
    [_table setDicParam:nil];
    _table.backgroundColor =[UIColor clearColor];
    [self.view addSubview:_table];
    
    __block typeof(self) weakself = self;
    [_table setCCellSelect:^(ScreentoneModel *model) {
        NSMutableDictionary *backDic=[[NSMutableDictionary alloc]init];
        [backDic setObject:model.S_name forKey:@"name"];
        [backDic setObject:model.S_uuid forKey:@"uuid"];
      //北京坐标(39.915175, 116.403906);

        if (model.S_latitude  ==nil||[model.S_latitude isEqualToString:@""]){
            [backDic setObject:@"39.915175" forKey:@"latitude"];

        }else
        {
            [backDic setObject:model.S_latitude forKey:@"latitude"];

        }
        if (model.S_longitude  ==nil||[model.S_longitude isEqualToString:@""]){

            [backDic setObject:@"116.403906" forKey:@"longitude"];

        }else
        {
            [backDic setObject:model.S_longitude forKey:@"longitude"];
            
        }
        weakself.backuiud(backDic);
        [weakself backController];
    }];

}

#pragma mark - UITextFieldDelegate
//还开始还没有字
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.table showCommon];

}

//点击完成键盘搜素按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setObject:textField.text forKey:@"keyword"];
    [_table setDicParam:dic];
    [textField resignFirstResponder];
    return YES;
}

//搜索按钮
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    [searchBar resignFirstResponder];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_searchField resignFirstResponder];
    [self.view endEditing:YES];
}
//clear
- (BOOL)textFieldShouldClear:(UITextField *)tefxtField
{
    [self.table showCommon];
    return YES;
    
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
   
        if ([[[UITextInputMode currentInputMode]primaryLanguage] isEqualToString:@"emoji"]) {
            return NO;
        }
   
    // 获得需要进行搜索的关键字
    NSString *shouldBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([shouldBeString isEqualToString:@""]) {
        [self.table showCommon];
        
    }else
    {
        // 搜索关联词汇
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        [dic setObject:shouldBeString forKey:@"keyword"];
        [_table setDicParam:dic];
    }
    return YES;
}



#pragma mark 定位
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //关闭地位
    
    
    [self onClickReverseGeocode];
    [_locService stopUserLocationService];
}
-(void)onClickReverseGeocode  //发送反编码请求的.
{
    isGeoSearch = false;
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};//初始化
    if (_locService.userLocation.location.coordinate.longitude!= 0
        && _locService.userLocation.location.coordinate.latitude!= 0) {
        //如果还没有给pt赋值,那就将当前的经纬度赋值给pt
        pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
            _locService.userLocation.location.coordinate.longitude
        };
    }
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];//初始化反编码请求
    reverseGeocodeSearchOption.reverseGeoPoint = pt;//设置反编码的店为pt
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];//发送反编码请求.并返回是否成功
    if(flag)
    {
        echo(@"反geo检索发送成功");
    }
    else
    {
        echo(@"反geo检索发送失败");
    }
}
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    

    for (int i = 0; i < result.poiList.count; i++) {
        
        BMKPoiInfo* poi = [result.poiList objectAtIndex:i];
        if (i==0) {
            //            _locationLab.text = poi.name;
            _latitude= poi.pt.latitude;
            _longitude = poi.pt.longitude;
#pragma mark 机构请求
          
            NSMutableDictionary *dataDic=[[NSMutableDictionary alloc]init];
            [dataDic setObject:[NSNumber numberWithDouble:_longitude] forKey:@"longitude"];
            [dataDic setObject:[NSNumber numberWithDouble:_latitude] forKey:@"latitude"];
            [_table setDicParam:dataDic];

            
        }
    }
}

/**
 *  生成图片
 *
 *  @param color  图片颜色
 *  @param height 图片高度
 *
 *  @return 生成的图片
 */
- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}
@end
